package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName : SpecGroupServiceImpl  //类名
 * @Description : 规格组service实现类  //描述
 * @Author : qingfeng  //作者
 * @Date: 2020-09-17 20:30  //时间
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    private final SpecParamService paramService;

    public SpecGroupServiceImpl(SpecParamService paramService) {
        this.paramService = paramService;
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long categoryId) {
        /**
         * @Description //TODO 查询规格组及规格参数
         * @Param [categoryId]
         * @return java.util.List<com.leyou.item.dto.SpecGroupDTO>
         */
        //查询规格组
        List<SpecGroupDTO> groupList = SpecGroupDTO.convertEntityList(query().eq("category_id", categoryId).list());
        if (CollectionUtils.isEmpty(groupList)){
            throw new LyException(404,"该分类下的规格组不存在！");
        }
        //查询规格参数
        List<SpecParamDTO> paramList = paramService.querySpecParams(categoryId,null,null);
        //对规格参数分组,groupId一致的在一组
        Map<Long,List<SpecParamDTO>> map = paramList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        //把参数放入group
        for (SpecGroupDTO groupDTO : groupList) {
            groupDTO.setParams(map.get(groupDTO.getId()));
        }
        return groupList;
    }
}
